package vn.ikame.android.boojtran.truyenbua;

import java.util.ArrayList;

import vn.ikame.android.boojtran.truyenbua.download.ItemListDowloadListener;
import vn.ikame.android.boojtran.truyenbua.download.ItemListDownload;
import vn.ikame.android.boojtran.truyenbua.logic.ImageManager;
import vn.ikame.android.boojtran.truyenbua.object.GA;
import vn.ikame.android.boojtran.truyenbua.object.Item;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.AbsListView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class ListItem extends SuperActivity implements
		AbsListView.OnScrollListener, ItemListDowloadListener {
	private ListView listview;
	private MenuListAdapter adapter;
	private AdView adView;
	public static ListItem menu;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		if (ImageManager.get().getListItem() == null
				|| ImageManager.get().getListItem().size() <= 0) {
			startActivity(new Intent(ListItem.this, Splash.class));
			this.finish();
		} else {
			initView();
			// admob
			adView = (AdView) this.findViewById(R.id.adView);
			adView.loadAd(new AdRequest());
			menu = this;

			if (store.isFirstTime()) {
				store.setFirstTime(false);
				showAboutDialog();
				// GA.trackGeneralView(APP_NAME + "_installApp");
				generalTracker.trackPageView(APP_NAME + "_installApp");
				generalTracker.dispatch();
				GA.trackAppView(APP_NAME + "_installApp");
			}

			if (!isShowWifiWarning && !isWifiConnected()) {
				isShowWifiWarning = true;
				showInfoDialog(
						"Kết nối",
						"Bạn nên sử dụng kết nối wifi để tải ảnh nhanh hơn và tiết kiệm dung lượng 3G. Chúc bạn vui vẻ!");
			}
		}
	}

	private void initView() {
		if (ImageManager.get().getListItem() == null
				|| ImageManager.get().getListItem().size() <= 0) {
			startActivity(new Intent(ListItem.this, Splash.class));
			this.finish();
		} else {
			listview = (ListView) findViewById(R.id.list);
			adapter = new MenuListAdapter(this, R.layout.list_item,
					ImageManager.get().getListItem());
			listview.setAdapter(adapter);
			listview.setOnScrollListener(this);
		}
	}

	private class MenuListAdapter extends ArrayAdapter<Item> {
		private ArrayList<Item> myList;
		private int textViewResourceId;

		public MenuListAdapter(Context context, int textViewResourceId,
				ArrayList<Item> list) {
			super(context, textViewResourceId, list);
			this.textViewResourceId = textViewResourceId;
			this.myList = list;
		}

		private View recycleOrCreateView(View v) {
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getContext()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(textViewResourceId, null);

				ViewHolder vh = new ViewHolder();
				vh.icon = (ImageView) v.findViewById(R.id.icon);
				vh.title = (TextView) v.findViewById(R.id.title);
				vh.subtitle = (TextView) v.findViewById(R.id.subtitle);
				vh.subtitle.setVisibility(View.GONE);
				v.setTag(vh);
			}
			v.setBackgroundResource(R.drawable.row_item_odd);
			return v;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			View view = recycleOrCreateView(convertView);
			ViewHolder vh = (ViewHolder) view.getTag();
			if (position < myList.size()) {
				vh.icon.setImageResource(R.drawable.new_icon);
				vh.title.setTextColor(getResources().getColor(R.color.white));
				if (isBelongArray(showedArr, myList.get(position).getId())) {
					vh.title.setTextColor(getResources().getColor(
							R.color.light_blue));
					vh.icon.setImageResource(R.drawable.laugh_icon);
				}
				vh.title.setText(myList.get(position).getTitle()); // (myList.size()
																	// -
																	// position)
																	// + ". "+
				if (position % 2 == 0)
					view.setBackgroundResource(R.drawable.row_item_even);
				// vh.subtitle.setText(myList.get(position).getSize());
				view.setTag(vh);
			}
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					ImageManager.get().setCurItem(position);
					if (!isBelongArray(showedArr, myList.get(position).getId())) {
						showedArr.add(myList.get(position).getId());
						store.setShowedArr(showedArr);
					}
					// Menu.this.finish();
					startActivity(new Intent(ListItem.this, Viewer.class));
				}
			});
			return view;
		}

		private class ViewHolder {
			ImageView icon;
			TextView title;
			TextView subtitle;
		}

	}

	@Override
	protected void onResume() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
		super.onResume();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			createExitMessage();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void createExitMessage() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setMessage("Bạn có muốn thoát ứng dụng?");
		alert.setPositiveButton("Có", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				if (noti.getType() == 3 && !noti.isShow()) {
					createNotificationAlert();
				} else {
					ListItem.this.finish();
					System.gc();
					android.os.Process.killProcess(android.os.Process.myPid());
				}
			}
		});

		alert.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		});
		alert.setCancelable(true);
		alert.show();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (previousTotal == totalItem)
			return;
		if (loading) {
			if (totalItemCount > previousTotal) {
				loading = false;
				previousTotal = totalItemCount;
			}
		}

		if (!loading
				&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
			requestServer(previousTotal, itemCount);
			loading = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	@Override
	protected void requestServer(int start, int count) {
		if (isOnline()) {
			ItemListDownload itemListDownload = new ItemListDownload(this, this);
			itemListDownload.start(start, count);
		} else {
			showNetworkDialog();
		}
	}

	@Override
	public void onDownloadFinish(ArrayList<Item> result, int start, int count) {
		if (result != null && result.size() > 0) {
			Log.e("TAG", "ok");
			ImageManager.get().getListItem().addAll(result);
			// previousTotal = ImageManager.get().getListItem().size();
			adapter.notifyDataSetChanged();
		} else {
			GA.trackAppView(APP_NAME + "_downloadListError");
			showReconnectDialog(start, count);
			Log.e("TAG", "lose");
		}
	}

	@Override
	public void onDownloadError(int start, int count) {
		GA.trackAppView(APP_NAME + "_downloadListError");
		showReconnectDialog(start, count);
	}
}
